﻿#include "CPresetAreaSetDialog.h"
#include <QFile>
#include "CDevBase.h"
#include "CHeader.h"
#include <QMessageBox>
#include <windows.h> // 包含 Windows API 头文件

//azq++ 20221104 start专家模式相关
#define def_rectLength 1000;   //视频框长度
#define def_rectWidth 600;     //视频框宽度
#define def_textLength 40;     //提示文本长度
#define def_textWidth 10;      //提示文本宽度
#define def_testSplit 50;       //文本和框的间隔

CPresetAreaSetDialog * g_pCSetDetectArea;
//在视频上绘制框和温度（矩形） 
void CALLBACK DrawTextRect(LONG lRealHandle, HDC hDc, DWORD dwUser)
{
	g_pCSetDetectArea->generateBoxArea(lRealHandle, hDc, dwUser);
	g_pCSetDetectArea->generateTemperatureMessage(lRealHandle, hDc, dwUser);
}

CPresetAreaSetDialog::CPresetAreaSetDialog(QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);
	initUI();
	initData();
}

CPresetAreaSetDialog::~CPresetAreaSetDialog()
{}

//设置相机数据
void CPresetAreaSetDialog::setCamearData(QString sSceneGuid, WORD wPresetNo, CDevBase* pDev, CDevDataCam *pDevDataCam)
{
	if (nullptr == pDevDataCam || nullptr == pDev)
	{
		return;
	}

	m_sGuid = sSceneGuid;
	m_wPresetNo = wPresetNo;
	m_pDev = pDev;
	m_pDevDataCam = pDevDataCam;

	/*获取句柄*/
	NET_DVR_PREVIEWINFO struPlayInfo;
	struPlayInfo.hPlayWnd = (HWND)ui.labelHwsp->winId(); //需要 SDK 解码时句柄设为有效值，仅取流不解码时可设为空
	//红外
	struPlayInfo.lChannel = m_pDevDataCam->m_sStruDeviceInfo.struChanInfo[1].iChanIndex;
	struPlayInfo.dwStreamType = 1; //0-主码流，1-子码流，2-码流 3，3-码流 4，以此类推
	struPlayInfo.dwLinkMode = 0; //0- TCP 方式，1- UDP 方式，2- 多播方式，3- RTP 方式，4-RTP/RTSP，5-RSTP/HTTP
	struPlayInfo.bBlocked = 0; //0- 非阻塞取流，1- 阻塞取流
	m_lHandle = NET_DVR_RealPlay_V40(m_pDevDataCam->m_sStruDeviceInfo.lLoginID, &struPlayInfo, nullptr, nullptr);

	playVideo();

	g_pCSetDetectArea = this;

	///*切换为专家模式*/
	//sctrinfo infotx;
	//infotx.m_hhwnd = (hwnd)ui.labelhwsp->winid();
	//infotx.m_sguid = m_sGuid;
	//infotx.m_nctrcmd = ensetmode;
	//infotx.m_nctrdevtype = ensubdev1;
	//infotx.m_nsubctrdevtype = encamer;
	//infotx.m_enmodetype = enexpertmode;
	//m_pdev->ctrdev(infotx);
}

//在视频上绘制温度信息
void CPresetAreaSetDialog::generateTemperatureMessage(LONG lRealHandle, HDC hdc, DWORD dwUser)
{
	if (nullptr == m_pDevDataCam)
	{
		return;
	}

	RECT widgetClientRect = { 0 };
	GetClientRect(m_hwnd, &widgetClientRect);//获取窗口客户区坐标

	double dMaxTemp = m_pDevDataCam->m_dAtcTempMax;
	double dAvgTemp = m_pDevDataCam->m_dAtcTempAverage;
	double dMinTemp = m_pDevDataCam->m_dAtcTempMin;

	double dCenterX = widgetClientRect.right * m_sDetectRect.centerPoint.dPercentX;
	double dCenterY = widgetClientRect.bottom * m_sDetectRect.centerPoint.dPercentY;
	double dWidth = def_textWidth;
	double dLength = def_textLength;

	RECT rectMaxTemp;  //最高温度
	char* cMaxTemp;
	QString sMaxTemp = "max: " + QString::number(QString::asprintf("%.1f", dMaxTemp).toDouble(), 'f', QLocale::FloatingPointShortest) + "℃";
	QByteArray bMaxTemp = sMaxTemp.toLocal8Bit();
	cMaxTemp = bMaxTemp.data();
	double dMaxTempX = dCenterX;
	double dMaxTempY = dCenterY;
	rectMaxTemp.left = dMaxTempX - dLength * 1.5;
	rectMaxTemp.top = dMaxTempY - dWidth;
	rectMaxTemp.right = dMaxTempX + dLength * 1.5;
	rectMaxTemp.bottom = dMaxTempY + dWidth;

	RECT rectAverageTemp;  //平均温度
	char* cAverageTemp;
	QString sAverageTemp = "ave: " + QString::number(QString::asprintf("%.1f", dAvgTemp).toDouble(), 'f', QLocale::FloatingPointShortest) + "℃";
	QByteArray bAverageTemp = sAverageTemp.toLocal8Bit();
	cAverageTemp = bAverageTemp.data();
	double dAverageTempX = dCenterX;
	double dAverageTempY = dCenterY + dWidth + 2;
	rectAverageTemp.left = dAverageTempX - dLength * 1.5;
	rectAverageTemp.top = dAverageTempY - dWidth;
	rectAverageTemp.right = dAverageTempX + dLength * 1.5;
	rectAverageTemp.bottom = dAverageTempY + dWidth;

	RECT rectMinTemp;  //最低温度
	char* cMinTemp;
	QString sMinTemp = "min: " + QString::number(QString::asprintf("%.1f", dMinTemp).toDouble(), 'f', QLocale::FloatingPointShortest) + "℃";
	QByteArray bMinTemp = sMinTemp.toLocal8Bit();
	cMinTemp = bMinTemp.data();
	double dMinTempX = dCenterX;
	double dMinTempY = dCenterY + dWidth * 2 + 2;
	rectMinTemp.left = dMinTempX - dLength * 1.5;
	rectMinTemp.top = dMinTempY - dWidth;
	rectMinTemp.right = dMinTempX + dLength * 1.5;
	rectMinTemp.bottom = dMinTempY + dWidth;

	COLORREF redColor = 0x000000FF; // 红色 (255, 0, 0)
	::SetTextColor(hdc, redColor);  //设置文本颜色
	::SetBkMode(hdc, TRANSPARENT);  //设置文本背景为透明色
	::DrawTextA(hdc, cMaxTemp, strlen(cMaxTemp), &rectMaxTemp, DT_RIGHT);
	::DrawTextA(hdc, cMinTemp, strlen(cMinTemp), &rectMinTemp, DT_RIGHT);
	::DrawTextA(hdc, cAverageTemp, strlen(cAverageTemp), &rectAverageTemp, DT_RIGHT);
}

//在视频上生成矩形方框
void CPresetAreaSetDialog::generateBoxArea(LONG lRealHandle, HDC hdc, DWORD dwUser)
{
	RECT widgetClientRect = { 0 };
	GetClientRect(m_hwnd, &widgetClientRect);//获取窗口客户区坐标

	double dCenterX = widgetClientRect.right * m_sDetectRect.centerPoint.dPercentX;
	double dCenterY = widgetClientRect.bottom * m_sDetectRect.centerPoint.dPercentY;

	RECT rectCenter;  //矩形框的中心点
	rectCenter.left = dCenterX - m_sDetectRect.dRectLength;
	rectCenter.top = dCenterY - m_sDetectRect.dRectWidth;
	rectCenter.right = dCenterX + m_sDetectRect.dRectLength;
	rectCenter.bottom = dCenterY + m_sDetectRect.dRectWidth;

	RECT rectPointA;  //左上角坐标
	char* cPointA;
	QString sPointAX = QString::number(QString::asprintf("%.1f", m_sDetectRect.pointA.pointItem.x()).toDouble(), 'f', QLocale::FloatingPointShortest);
	QString sPointAY = QString::number(QString::asprintf("%.1f", m_sDetectRect.pointA.pointItem.y()).toDouble(), 'f', QLocale::FloatingPointShortest);
	QString sPointA = "(" + sPointAX + "," + sPointAY + ")";
	QByteArray bPointA = sPointA.toLocal8Bit();
	cPointA = bPointA.data();
	double dPointAX = dCenterX - m_sDetectRect.dRectLength - def_testSplit - def_textLength;
	double dPointAY = dCenterY - m_sDetectRect.dRectWidth;
	rectPointA.left = dPointAX - def_textLength;
	rectPointA.top = dPointAY - def_textWidth;
	rectPointA.right = dPointAX + def_textLength;
	rectPointA.bottom = dPointAY + def_textWidth;

	RECT rectPointB;  //右上角坐标
	char* cPointB;
	QString sPointBX = QString::number(QString::asprintf("%.1f", m_sDetectRect.pointB.pointItem.x()).toDouble(), 'f', QLocale::FloatingPointShortest);
	QString sPointBY = QString::number(QString::asprintf("%.1f", m_sDetectRect.pointB.pointItem.y()).toDouble(), 'f', QLocale::FloatingPointShortest);
	QString sPointB = "(" + sPointBX + "," + sPointBY + ")";
	QByteArray bPointB = sPointB.toLocal8Bit();
	cPointB = bPointB.data();
	double dPointBX = dCenterX + m_sDetectRect.dRectLength + def_testSplit + def_textLength;
	double dPointBY = dCenterY - m_sDetectRect.dRectWidth;
	rectPointB.left = dPointBX - def_textLength;
	rectPointB.top = dPointBY - def_textWidth;
	rectPointB.right = dPointBX + def_textLength;
	rectPointB.bottom = dPointBY + def_textWidth;

	RECT rectPointC;  //右边下角坐标
	char* cPointC;
	QString sPointCX = QString::number(QString::asprintf("%.1f", m_sDetectRect.pointC.pointItem.x()).toDouble(), 'f', QLocale::FloatingPointShortest);
	QString sPointCY = QString::number(QString::asprintf("%.1f", m_sDetectRect.pointC.pointItem.y()).toDouble(), 'f', QLocale::FloatingPointShortest);
	QString sPointC = "(" + sPointCX + "," + sPointCY + ")";
	QByteArray bPointC = sPointC.toLocal8Bit();
	cPointC = bPointC.data();
	double dPointCX = dCenterX + m_sDetectRect.dRectLength + def_testSplit + def_textLength;
	double dPointCY = dCenterY + m_sDetectRect.dRectWidth;
	rectPointC.left = dPointCX - def_textLength;
	rectPointC.top = dPointCY - def_textWidth;
	rectPointC.right = dPointCX + def_textLength;
	rectPointC.bottom = dPointCY + def_textWidth;

	RECT rectPointD;  //左下角坐标
	char* cPointD;
	QString sPointDX = QString::number(QString::asprintf("%.1f", m_sDetectRect.pointD.pointItem.x()).toDouble(), 'f', QLocale::FloatingPointShortest);
	QString sPointDY = QString::number(QString::asprintf("%.1f", m_sDetectRect.pointD.pointItem.y()).toDouble(), 'f', QLocale::FloatingPointShortest);
	QString sPointD = "(" + sPointDX + "," + sPointDY + ")";
	QByteArray bPointD = sPointD.toLocal8Bit();
	cPointD = bPointD.data();
	double dPointDX = dCenterX - m_sDetectRect.dRectLength - def_testSplit - def_textLength;
	double dPointDY = dCenterY + m_sDetectRect.dRectWidth;
	rectPointD.left = dPointDX - def_textLength;
	rectPointD.top = dPointDY - def_textWidth;
	rectPointD.right = dPointDX + def_textLength;
	rectPointD.bottom = dPointDY + def_textWidth;

	//// 修改直线的颜色 , 粗细 .
	//LOGBRUSH rectLine;
	//rectLine.lbStyle = BS_SOLID;  //纯色画笔
	//rectLine.lbColor = RGB(0, 0, 0);  //颜色
	//rectLine.lbHatch = 0;

	COLORREF whiteColor = 0x00FFFFFF; // 红色 (255, 0, 0)
	::SetTextColor(hdc, whiteColor);  //设置文本颜色
	::SetBkMode(hdc, TRANSPARENT);  //设置文本背景为透明色
	::DrawTextA(hdc, cPointA, strlen(cPointA), &rectPointA, DT_LEFT);
	::DrawTextA(hdc, cPointB, strlen(cPointB), &rectPointB, DT_RIGHT);
	::DrawTextA(hdc, cPointC, strlen(cPointC), &rectPointC, DT_LEFT);
	::DrawTextA(hdc, cPointD, strlen(cPointD), &rectPointD, DT_RIGHT);

	COLORREF redColor = 0x000000FF; // 红色 (255, 0, 0)
	HPEN pen = ::CreatePen(PS_SOLID, 1, redColor);
	HPEN oldPen = (HPEN)::SelectObject(hdc, pen);
	::SelectObject(hdc, oldPen);
	::DrawFocusRect(hdc, &rectCenter);
	::DeleteObject(pen);
	::DeleteObject(oldPen);
}

void CPresetAreaSetDialog::mouseMoveEvent(QMouseEvent * event)
{
	QPoint point = event->pos();
	point.setY(point.y() - 30);
	if (1 == 1)
	{
		QPointF pointC = point;
		m_mapGraphPoints.insert("3", pointC);
		QPointF pointA = m_mapGraphPoints.value("1");
		generateBox(pointA, pointC);
		//获取坐标信息 绘制方框
		generateRectPointInfo();
	}
	
	return QWidget::mouseMoveEvent(event);
}

void CPresetAreaSetDialog::mousePressEvent(QMouseEvent * event)
{
	QPoint point = event->pos();
	point.setY(point.y() - 30);
	if (event->button() == Qt::LeftButton)
	{
		//开启画图
		if (!m_bIsDraw)
		{
			drawRectBox();
			m_bIsDraw = true;
		}

		if (1 == 1)
		{
			QPointF pointA = point;
			m_mapGraphPoints.insert("1", pointA);
			QPointF pointC = m_mapGraphPoints.value("3");
			generateBox(pointA, pointC);
			//获取坐标信息 绘制方框
			generateRectPointInfo();
		}
	}
	if (event->button() == Qt::RightButton)
	{
		bool bStatus = false;

		////获取坐标信息 绘制方框
		//generateRectPointInfo();
		//drawRectBox();

		//qDebug() << "(" << m_pointA.x() << "," << m_pointA.y() << ")" << "---" << "(" << m_pointB.x() << "," << m_pointB.y() << ")";
		//qDebug() << "(" << m_pointC.x() << "," << m_pointC.y() << ")" << "---" << "(" << m_pointD.x() << "," << m_pointD.y() << ")";

		if (m_sDetectRect.centerPoint.dPercentX == 0 && m_sDetectRect.centerPoint.dPercentY == 0)
		{
			messageBox(0, QString::fromLocal8Bit("还没有框选区域!"));
			return;
		}

		int ret = messageBox(3, QString::fromLocal8Bit("是否确定框选区域为预设区域?"));
		switch (ret)
		{
		case QMessageBox::Yes:
			m_sPersetData.wPresetNo = m_wPresetNo;
			m_sPersetData.wDistance = ui.lineEditDistance->text().toInt();
			//未框选类型
			if (1 == 1)
			{
				SCtrInfo infoTx;
				infoTx.m_hHwnd = (HWND)ui.labelHwsp->winId();
				infoTx.m_sGuid = m_sGuid;
				infoTx.m_nCtrCmd = enSetPresetArea;
				infoTx.m_nCtrDevType = enSubDev1;
				infoTx.m_nSubCtrDevType = enCamer;
				infoTx.m_stPersetAreaRect = m_sDetectRect;
				infoTx.m_stPersetAreaParam = m_sPersetData;
				bStatus = m_pDev->ctrDev(infoTx); 
			}
			
			if (false == bStatus)
			{
				messageBox(0, QString::fromLocal8Bit("监测区域配置失败!"));
				return;
			}

			messageBox(0, QString::fromLocal8Bit("监测区域配置成功!"));
			break;
		case QMessageBox::No:
			break;
		default:
			break;
		}
	}
	return QWidget::mousePressEvent(event);
}

void CPresetAreaSetDialog::mouseReleaseEvent(QMouseEvent * event)
{
	QPoint point = event->pos();
	point.setY(point.y() - 30);
	if (1 == 1)
	{
		if (event->button() == Qt::LeftButton)
		{
			m_mapGraphPoints.insert("3", point);
			//获取坐标信息 绘制方框
			generateRectPointInfo();
		}
	}
	
	return QWidget::mousePressEvent(event);
}

void CPresetAreaSetDialog::closeEvent(QCloseEvent * event)
{
	//azq++ 20221103 关闭红外摄像头
	bool bResult = stopVideo();
	if (bResult)
	{
		ui.labelHwsp->setUpdatesEnabled(true);
		m_bIsDraw = false;
	}

	/*切换为普通模式*/
	//SCtrInfo infoTx;
	//infoTx.m_hHwnd = (HWND)ui.labelHwsp->winId();
	//infoTx.m_sGuid = m_sGuid;
	//infoTx.m_nCtrCmd = enSetMode;
	//infoTx.m_nCtrDevType = enSubDev1;
	//infoTx.m_nSubCtrDevType = enCamer;
	//infoTx.m_enModeType = enNormalMode;
	//m_pDev->ctrDev(infoTx);
}

void CPresetAreaSetDialog::initUI()
{
	QIcon icon(":/icon/Rob/Rob.ico");
	setWindowIcon(icon);
	setWindowTitle(A2T("预置点区域配置"));
	setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);

	setStyleSheetFile();
}

void CPresetAreaSetDialog::initData()
{
	m_sGuid = "";
	m_pDevDataCam = nullptr;
	m_pDev = nullptr;
	m_nRectLength = def_rectLength;
	m_nRectWidth = def_rectWidth;
	m_lHandle = -1;
	m_hwnd = (HWND)(ui.labelHwsp->winId());
	setWindowFlags(windowFlags()& ~Qt::WindowMaximizeButtonHint);
	setFixedSize(1000, 600);
	m_sDetectRect.centerPoint.dPercentX = 0;
	m_sDetectRect.centerPoint.dPercentY = 0;

	//初始化距离配置参数
	m_pButtonGroup = new QButtonGroup(this);
	m_pButtonGroup->addButton(ui.radioButtonM, 0);
	m_pButtonGroup->addButton(ui.radioButtonYc, 1);
	m_pButtonGroup->addButton(ui.radioButtonLm, 2);
	ui.lineEditDistance->setText(QString::number(2));
	ui.radioButtonM->setChecked(1);
	connect(m_pButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(slotChangeDistanceUnity(int)));
	m_sPersetData.wPresetNo = 0;
	m_sPersetData.wDistance = 0;
	m_sPersetData.byDistanceUnit = 0;

	//初始化绘制框配置参数
	connect(ui.pushButtonClear, SIGNAL(clicked()), this, SLOT(slotClearSelect()));
	m_sPersetData.wPresetNo = 0;
	m_sPersetData.wDistance = 0;
	m_sPersetData.byDistanceUnit = 0;
	m_nPointNum = 0;
	m_bIsDraw = false;
}

//设置样式文件
void CPresetAreaSetDialog::setStyleSheetFile()
{
	QString sQssPath = ":/qss/styleSheet.css";
	QFile qss(sQssPath);
	qss.open(QFile::ReadOnly);
	this->setStyleSheet(qss.readAll());
}

//绘制矩形方框
bool CPresetAreaSetDialog::drawRectBox()
{
	if (1 == 1)
	{
		if (!NET_DVR_RigisterDrawFun(m_lHandle, DrawTextRect, NULL))
		{
			//qDebug() << "draw rect failed";
			//qDebug() << "error code" << NET_DVR_GetLastError();
			slotClearSelect();
			return false;
		}
	}

	return true;
}

//生成通过坐标（ A-左上角  C-右下角）生成矩形
void CPresetAreaSetDialog::generateBox(QPointF pointA, QPointF pointC)
{
	int nX = qMin(pointA.x(), pointC.x());
	int nY = qMin(pointA.y(), pointC.y());
	int nHeightB = abs(pointC.y() - pointA.y());
	int nWidthB = abs(pointC.x() - pointA.x());

	QPointF pointB;
	pointB.setX(pointC.x());
	pointB.setY(pointA.y());
	m_mapGraphPoints.insert("2", pointB);

	QPointF pointD;
	pointD.setX(pointA.x());
	pointD.setY(pointC.y());
	m_mapGraphPoints.insert("4", pointD);
}

//生成矩形坐标信息
void CPresetAreaSetDialog::generateRectPointInfo()
{
	QPointF pointA = m_mapGraphPoints.value("1");
	QPointF pointB = m_mapGraphPoints.value("2");
	QPointF pointC = m_mapGraphPoints.value("3");
	QPointF pointD = m_mapGraphPoints.value("4");

	//获取左上角坐标参数
	m_sDetectRect.pointA.pointItem = pointA;
	m_sDetectRect.pointA.dPercentX = pointA.x() / m_nRectLength;
	m_sDetectRect.pointA.dPercentY = pointA.y() / m_nRectWidth;

	//获取右上角坐标参数
	m_sDetectRect.pointB.pointItem = pointB;
	m_sDetectRect.pointB.dPercentX = pointB.x() / m_nRectLength;
	m_sDetectRect.pointB.dPercentY = pointB.y() / m_nRectWidth;

	//获取左下角坐标参数
	m_sDetectRect.pointC.pointItem = pointC;
	m_sDetectRect.pointC.dPercentX = pointC.x() / m_nRectLength;
	m_sDetectRect.pointC.dPercentY = pointC.y() / m_nRectWidth;

	//获取右下角坐标参数
	m_sDetectRect.pointD.pointItem = pointD;
	m_sDetectRect.pointD.dPercentX = pointD.x() / m_nRectLength;
	m_sDetectRect.pointD.dPercentY = pointD.y() / m_nRectWidth;

	//获取中心点参数
	QPointF centerPointer;
	double minX = qMin(pointA.x(), pointC.x());
	double minY = qMin(pointA.y(), pointC.y());
	double centerX = abs(pointA.x() - pointC.x()) / 2;
	double centerY = abs(pointA.y() - pointC.y()) / 2;
	centerPointer.setX(minX + centerX);
	centerPointer.setY(minY + centerY);
	m_sDetectRect.centerPoint.pointItem = centerPointer;
	m_sDetectRect.centerPoint.dPercentX = centerPointer.x() / m_nRectLength;
	m_sDetectRect.centerPoint.dPercentY = centerPointer.y() / m_nRectWidth;

	//矩形长宽的半值
	m_sDetectRect.dRectLength = centerX;
	m_sDetectRect.dRectWidth = centerY;
}

//播放视频
bool CPresetAreaSetDialog::playVideo()
{
	SCtrInfo infoHw;
	infoHw.m_hHwnd = (HWND)ui.labelHwsp->winId();
	infoHw.m_sGuid = m_sGuid;
	infoHw.m_nCtrCmd = enCRealPlay;
	infoHw.m_nCtrDevType = enSubDev1;
	infoHw.m_nSubCtrDevType = enIR;
	bool bHwRet = m_pDev->ctrDev(infoHw);
	return bHwRet;
}

//停止播放视频
bool CPresetAreaSetDialog::stopVideo()
{
	SCtrInfo infoHw;
	infoHw.m_hHwnd = (HWND)ui.labelHwsp->winId();
	infoHw.m_sGuid = m_sGuid;
	infoHw.m_nCtrCmd = enCStopRealPlay;
	infoHw.m_nCtrDevType = enSubDev1;
	infoHw.m_nSubCtrDevType = enIR;
	bool bHwRet = m_pDev->ctrDev(infoHw);
	return bHwRet;
}

//切换距离的单位
void CPresetAreaSetDialog::slotChangeDistanceUnity(int nType)
{
	switch (nType)
	{
	case 0:
		m_sPersetData.byDistanceUnit = 0;
		break;
	case 1:
		m_sPersetData.byDistanceUnit = 1;
		break;
	case 2:
		m_sPersetData.byDistanceUnit = 2;
		break;
	default:
		break;
	}
}

//清除当前框选
void CPresetAreaSetDialog::slotClearSelect()
{
	m_mapGraphPoints.clear();
	m_nPointNum = 0;
}